import java.io.BufferedReader
import java.io.File
import java.io.PrintStream
import java.io.InputStreamReader
import java.time.LocalDateTime
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

fun adbShell(inCmd: String, deviceSN: String) {
    Run("adb -s $deviceSN shell $inCmd")
}

fun Run(inCmd: String, inWorkdir: String? = null) {
    Run(inCmd.split(" "), inWorkdir)
}

fun Run(inCmd: List<String>, inWorkdir: String? = null) {
    println("Run: $inCmd")
    val pb: ProcessBuilder = ProcessBuilder(inCmd)
            .directory(File(inWorkdir ?: "."))
            .redirectErrorStream(true)
    val p = pb.start()
    val reader = BufferedReader(InputStreamReader(p.inputStream))
    while (true) {
        val line = reader.readLine() ?: break
        println(line)
    }
    p.waitFor()
    if (0 != p.exitValue()) {
        throw RuntimeException()
    }
}

fun CheckOutput(inCmd: String, inWorkdir: String? = null): List<String> {
    return CheckOutput(inCmd.split(" "), inWorkdir)
}

fun CheckOutput(inCmd: List<String>, inWorkdir: String? = null): List<String> {
    println("Run: $inCmd")
    val ret = mutableListOf<String>()
    val pb: ProcessBuilder = ProcessBuilder(inCmd)
            .directory(File(inWorkdir ?: "."))
            .redirectErrorStream(true)
    val p = pb.start()
    val reader = BufferedReader(InputStreamReader(p.inputStream))
    while (true) {
        val line = reader.readLine() ?: break
        ret.add(line)
    }
    p.waitFor()
    if (0 != p.exitValue()) {
        throw RuntimeException()
    }
    return ret
}

fun wol(macaddr: String) {
    for (i in 0..3) {
        Run("wakeonlan $macaddr")
        TimeUnit.SECONDS.sleep(3)
    }
}

fun isDeviceOnline(deviceSN: String): Boolean {
    var ret = false
    CheckOutput("adb devices").forEach {
        if (it.contains(deviceSN)) {
            ret = true
        }
    }
    return ret
}

fun isDeviceBootComplete(deviceSN: String): Boolean {
    val bootComp = CheckOutput("adb -s $deviceSN shell getprop sys.boot_completed")
    if (bootComp.size == 1 && bootComp[0] == "1") {
        return true
    }
    return false
}

fun recordLogcat(deviceSN: String) {
    try {
        Run("adb -s $deviceSN wait-for-device")
        Run("adb -s $deviceSN logcat")
    } catch (e: Exception) {
        //ignore
    }
}


if (args.size != 1) {
    println("usage: prog <deviceId>")
    exitProcess(1)
}

val logFile = PrintStream(File("log.log")); 
System.setOut(logFile)

var i: Int = 0
while (true) {
    println("=".repeat(15) + " Round $i " + "=".repeat(15))
    println(LocalDateTime.now())
    recordLogcat(args[0])
    println(LocalDateTime.now())
    println("Round $i done\n")
    if (i == Int.MAX_VALUE) {
        println("FINISH")
        break
    }
    i++
    TimeUnit.SECONDS.sleep(5)
}

